/*
 * <p>Copyright® 2009-2022 东软 IT 实训中心版权所有。</p>
 */

package com.max.back.doctor.api;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.max.back.common.http.ResponseResult;
import com.max.back.doctor.form.ExaminationForm;
import com.max.back.doctor.service.CheckItemService;
import com.max.back.doctor.service.CodeNameService;
import com.max.back.entity.CheckItem;
import com.max.back.entity.Examination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 辛凤文 forward.seen@foxmail.com
 * @version 1.0
 * @description <p>
 * <code>CheckItemApi</code>
 *
 * </p>
 * @time 2022/7/25 22:35
 * @see
 */
@RestController
@CrossOrigin
@RequestMapping("/checkItem")
@Validated
public class CheckItemApi {

    @Autowired
    private CheckItemService checkItemService;

    @Autowired
    private CodeNameService codeNameService;

    @PostMapping("/commitInfoToChecks")
    public ResponseResult<Boolean> commitInfoToChecks(@RequestBody @Validated ExaminationForm examinationForm) {
        System.out.println(examinationForm);
        Object checkId = examinationForm.getExaminationId();
        // 删除所有checkId相关的检查项
        Map<String, Object> map = MapUtil.builder("CHECK_ID", checkId).build();
        checkItemService.removeByMap(map);
        List<CheckItem> checkItems = examinationForm.getSelectedOptionKeys().stream().map(e -> {
            // 重新添加checkId相关的检查项
            String[] splitName = codeNameService.getValueByKey(e).split("-");
            CheckItem checkItem = new CheckItem();
            checkItem.setId(IdUtil.simpleUUID());
            checkItem.setCheckId(examinationForm.getExaminationId());
            checkItem.setName(splitName[0]);
            checkItem.setPart(splitName[1]);
            checkItem.setCheckCode(e);
            return checkItem;
        }).collect(Collectors.toList());
        return ResponseResult.getSuccessResult(checkItemService.saveBatch(checkItems));
    }

    @GetMapping("/getCheckCodesIdListByCheckId")
    public ResponseResult<Object> getCheckCodesIdListByCheckId(@NotBlank String checkId) {
        return ResponseResult.getSuccessResult(checkItemService.getCheckCodesByCheckId(checkId));
    }

    @GetMapping("/getCheckResultInfo")
    public ResponseResult<List<Map<String, Object>>> getCheckResultInfo(@NotBlank String checkId) {
        return ResponseResult.getSuccessResult(checkItemService.getCheckResultInfoByCheckId(checkId));
    }
}